package com.hh.bidding.utils;

import org.apache.catalina.connector.ClientAbortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    protected static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static void downloadFiles(String FILENAME, String file, HttpServletResponse response) {
        try {
            logger.debug("file:{}",file);
            // 设置响应头，指定为zip文件
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=files.zip");
            // 设置缓冲区大小
            response.setBufferSize(1024 * 1024); // 1MB缓冲区

            // 创建ZipOutputStream
            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
            //拆分文件名
            String[] fileNames = file.split(",");
            // 将多个文件打包到zip文件中
            for (String fileName : fileNames) {
                String name = StringPathUtils.replaceHttpToNull(fileName);
                logger.debug("name:{}",FILENAME + "/" + name);
                Path filePath = Paths.get(FILENAME + "/" + name);
                ZipEntry zipEntry = new ZipEntry(StringPathUtils.subStringLastString(fileName));
                zipOut.putNextEntry(zipEntry);

                // 将文件内容写入ZipOutputStream
                Files.copy(filePath, zipOut);
            }
            // 关闭ZipOutputStream
            zipOut.close();
        } catch (ClientAbortException e) {
            // 客户端中断连接，这是正常行为，无需处理或只需记录日志
            logger.debug("客户端中断了下载连接", e);
        } catch (IOException e) {
            // 其他IO异常
            logger.error("com.hh.bidding.utils.FileUtil.downloadFiles 文件下载IO异常", e);
            if (!response.isCommitted()) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }

}
